//
//  ViewController.swift
//  GitTFGUI
//
//  Created by Samuel Richard Magny on 2015-08-29.
//  Copyright (c) 2015 Samuel Richard Magny. All rights reserved.
//

import Cocoa
import SwiftTools
import TFSClient

class MainViewController: NSViewController, NSTextFieldDelegate, NSTableViewDelegate {

    private let cloneButtonSegueString:String = "CloneButtonSegue"
    
    @IBOutlet var pendingFilesTableView: FilesTableView!
    @IBOutlet var fileDirectorySelectorButton: NSButton!
    @IBOutlet var workingDirectoryTextField: CopyPasteCutNSTextField!
    
    @IBOutlet var filesCountLabel: FileCountLabel!
    
    let viewModel: MainViewModel
    let applicationModel:ApplicationModel
    
    private let pendingFilesTableViewDataSource:FilesTableViewDataSource = FilesTableViewDataSource()
    
    required init?(coder aDecoder: NSCoder) {
        self.applicationModel = (NSApplication.sharedApplication().delegate as! AppDelegate).applicationModel
        viewModel = MainViewModel(tfsClient: self.applicationModel.tfsClient)
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let notificationCenter = self.applicationModel.notificationCenter
        notificationCenter.subscribe(self, selector: "workingDirectoryChanged:", identifier: TFSClientNotification.NotificationType.WorkingDirectoryChanged)
        
        self.pendingFilesTableView.setDataSource(pendingFilesTableViewDataSource)
        self.pendingFilesTableView.setDelegate(self)
        
        workingDirectoryTextField.delegate = self
        
        filesCountLabel.stringValue = "0"
    }
    
    override func viewDidAppear() {
        if(!viewModel.areCredentialsValids()) {
            let settingsViewController = self.storyboard?.instantiateControllerWithIdentifier(SettingsViewController.StoryboardId) as! SettingsViewController;

            self.presentViewControllerAsSheet(settingsViewController)
        }
    }
    
    dynamic private func workingDirectoryChanged(notification: WorkingDirectoryChangedNotification)
    {
        self.workingDirectoryTextField.stringValue = notification.directory

        if(notification.isValid)
        {
            viewModel.retreivePendingChangeFiles({ (files) -> () in
                self.pendingFilesTableViewDataSource.source = files
                
                dispatch_async(dispatch_get_main_queue(),{
                    self.filesCountLabel.formatedStringValue = String(files.count)
                    self.pendingFilesTableView.reloadData()
                })
            })
        }
        else
        {
            self.pendingFilesTableViewDataSource.source = []
            self.pendingFilesTableView.reloadData()
        }
    }
    
    
    @IBAction func fileDirectorySelectorButtonPressed(sender: NSButton) {
        let openPanel = NSOpenPanel()

        openPanel.canChooseDirectories = true
        openPanel.canChooseFiles = false

        openPanel.directoryURL = NSURL(fileURLWithPath: viewModel.workingDirectory)

        openPanel.prompt = "Select"
        let window = NSApplication.sharedApplication().windows[0]
        openPanel.beginSheetModalForWindow(window) { (result) -> Void in
            
            if result == NSFileHandlingPanelOKButton
            {
                let workingDirectoryPathUrl = openPanel.URL!
                let workingDirectoryPath: NSString = workingDirectoryPathUrl.path!
                
                self.viewModel.workingDirectory = workingDirectoryPath as String
            }
        }
    }

    
    //NSTextFieldDelegate
    //----------------------------------------------------------
    override func controlTextDidChange(aNotification: NSNotification) {
        
        if(aNotification.object! as! NSObject == self.workingDirectoryTextField) {
            viewModel.workingDirectory = workingDirectoryTextField.stringValue
        }
    }
    

    //NSTableViewDelegate
    //----------------------------------------------------------
    func tableView(tableView: NSTableView, shouldEditTableColumn tableColumn: NSTableColumn?, row: Int) -> Bool {
        
        if(tableColumn?.identifier == FilesTableView.CheckColumnIdentifier)
        {
            return true
        }
        
        return false
    }

    
    @IBAction func selectAllFiles(sender: AnyObject) {
        self.pendingFilesTableView.selectAll(self)
    }
    
}

